//
//  BaseTableController.m
//  
//
//  Created by 远成物流 on 2017/5/15.
//
//

#import "BaseTableController.h"
#import "BHTTPSessionManager.h"
#import "BaseTableCell.h"
#import <MJRefresh/MJRefresh.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import <MJExtension/MJExtension.h>
#import <SDWebImage/SDImageCache.h>
//#import <ZFPlayer/ZFPlayerModel.h>
#import <ZFPlayer/ZFPlayer.h>

@interface BaseTableController ()<ZFPlayerDelegate>

/** 当前最后一条帖子数据的描述信息，专门用来加载下一页数据 */
@property(nonatomic,strong)NSString *maxtime;
/** 所有的帖子数据 */
@property(nonatomic,strong)NSMutableArray<EssenceTopic *> *topics;
/** 请求管理者 */
@property(nonatomic,strong)BHTTPSessionManager *manager;

@property (nonatomic, strong) ZFPlayerView        *playerView;

@end

@implementation BaseTableController

/* cell的重用标识 */
static NSString * const BaseTableCellID = @"BaseTableCellID";

-(EssenceTopicType)type{
    return 0;
}

-(BHTTPSessionManager *)manager{
    if (_manager == nil) {
        _manager = [BHTTPSessionManager manager];
    }
    
    return _manager;
}

- (ZFPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [ZFPlayerView sharedPlayerView];
        _playerView.delegate = self;
        // 当cell播放视频由全屏变为小屏时候，不回到中间位置
        _playerView.cellPlayerOnCenter = NO;
        
        // 当cell划出屏幕的时候停止播放
        // _playerView.stopPlayWhileCellNotVisable = YES;
        //（可选设置）可以设置视频的填充模式，默认为（等比例填充，直到一个维度到达区域边界）
        // _playerView.playerLayerGravity = ZFPlayerLayerGravityResizeAspect;
        // 静音
        // _playerView.mute = YES;
    }
    return _playerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = Color(206, 206, 206);
    
    self.tableView.contentInset = UIEdgeInsetsMake(TitleViewHeight, 0, TabbarMaxHeight, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //注册cell
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([BaseTableCell class]) bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:BaseTableCellID];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabbarDidRepeatClicked) name:TabBarButtonDidRepeatClickedNotification object:nib];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(titleDidRepeatClicked) name:TitleButtonDidRepeatClickedNotification object:nib];
    
    [self refresh];
}

//刷新控件
-(void)refresh{
    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

#pragma tabbar重复点击
-(void)tabbarDidRepeatClicked{
    // 重复点击的不是精华按钮
    if (self.view.window == nil) {
        return;
    }
    
    // 显示在正中间的不是VideoViewController
    if (self.tableView.scrollsToTop == NO) {
        return;
    }
    
    //刷新数据
    [self.tableView.mj_header beginRefreshing];
}

#pragma 标题重复点击
-(void)titleDidRepeatClicked{
    [self tabbarDidRepeatClicked];
}

#pragma 下拉刷新
-(void)loadData{
    //取消之前的请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    //设置参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    
    [self.manager GET:CommonURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 存储maxtime
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        self.topics = [EssenceTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code != NSURLErrorCancelled) {
            //非取消任务导致
            [SVProgressHUD showErrorWithStatus:@"网络繁忙，请稍后再试"];
        }
        
        [self.tableView.mj_header endRefreshing];
    }];
}

#pragma 上拉加载更多
-(void)loadMoreData{
    //取消之前的请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    //设置参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    params[@"maxtime"] = self.maxtime;
    
    [self.manager GET:CommonURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        NSArray *array = [EssenceTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        //累加到旧数组的后面
        [self.topics addObjectsFromArray:array];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error.code != NSURLErrorCancelled) {
            //非取消任务导致
            [SVProgressHUD showErrorWithStatus:@"网络繁忙，请稍后再试"];
        }
        
        [self.tableView.mj_footer endRefreshing];
    }];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // 根据数据量显示或者隐藏footer
    self.tableView.mj_footer.hidden = (self.topics.count == 0);
    return self.topics.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BaseTableCell *cell = [tableView dequeueReusableCellWithIdentifier:BaseTableCellID];
    
    cell.topic = self.topics[indexPath.section];
    
    __block NSIndexPath *weakIndexPath = indexPath;
    __block BaseTableCell *weakCell     = cell;
    __weak typeof(self)  weakSelf      = self;
    
    //播放视频
    cell.playBlock = ^(id sender){
        
        ZFPlayerModel *playerModel = [[ZFPlayerModel alloc] init];
        
        playerModel.videoURL         = [NSURL URLWithString:weakCell.topic.videouri];
        playerModel.placeholderImageURLString = weakCell.topic.image0;
        playerModel.tableView       = weakSelf.tableView;
        playerModel.indexPath        = weakIndexPath;
//         player的父视图
        playerModel.fatherView = weakCell.videoView;

        // 设置播放控制层和model
        [weakSelf.playerView playerControlView:nil playerModel:playerModel];
        // 下载功能
        weakSelf.playerView.hasDownload = YES;
        // 自动播放
        [weakSelf.playerView autoPlayTheVideo];
        
    };
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.topics[indexPath.section].cellHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }
    return 10;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //清楚内存缓存
    [[SDImageCache sharedImageCache] clearMemory];
    
    //去除section header悬停
    CGFloat sectionHeaderHeight = 10;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
    
    self.tableView.contentInset = UIEdgeInsetsMake(TitleViewHeight, 0, TabbarMaxHeight, 0);
}

@end
